package com.wqj.kyee.gps

import android.app.DialogFragment
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wqj.kyee.gps.util.ToastUtil
import kotlinx.android.synthetic.main.activity_car_info_dialog.*
import kotlinx.android.synthetic.main.activity_car_info_dialog.view.*
import org.jetbrains.anko.ctx

class CarInfoDialog() : DialogFragment(), View.OnClickListener {

    lateinit var mCarInfoUpdatedListner : OnCarInfoUpdatedListener

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.activity_car_info_dialog, container)
        view.okView.setOnClickListener(this)
        view.cancelView.setOnClickListener(this)
        return view
    }

    fun setCarInfoUpdatedListerner(listener : OnCarInfoUpdatedListener) {
        mCarInfoUpdatedListner = listener
    }


    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.okView -> {
                //storeCarNumber(carNumInput.text.toString())
                mCarInfoUpdatedListner.carInfoUpdated(carNumInput.text.toString().trim())
                //ToastUtil.show(ctx, "保存车牌号成功")
                this.dismiss()
            }
            R.id.cancelView -> {
                mCarInfoUpdatedListner.carInfoUpdated("")
                this.dismiss()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        var number = getCarNumber()
        if (number != null) {
            carNumInput.setText(number)
        }
    }

    fun getCarNumber():String? {
        var sp = ctx.getSharedPreferences("carInfo", AppCompatActivity.MODE_PRIVATE)

        return sp.getString("carInfo", null)
    }

    fun storeCarNumber(number: String) {
        var sp = ctx.getSharedPreferences("carInfo", AppCompatActivity.MODE_PRIVATE)
        var editor = sp.edit()

        if (number.isEmpty()) {
            return
        }

        editor.putString("carNum", number)

        editor.commit()
    }
}
